#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>

#define PORTNO 12311

#define byte unsigned char

int main(int argc, char *argv[])
{
	int sockfd, portno, n;
	struct sockaddr_in serv_addr;
	struct hostent *server;

	byte buffer[256];
	
	if(argc < 2)
	{
		printf("Please supply a hostname\n");
		return -1;
	}

	portno = PORTNO;
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if(sockfd<0)
	{
		printf("Could not open socket!");
		return -1;
	}

	printf("Socket opened...\n");

	server = gethostbyname(argv[1]);
	if(server == NULL)
	{
		printf("No such host found!\n");
		//close(sockfd);
		return -1;
	}

	memset(&serv_addr,0,sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	memcpy(server->h_addr,&serv_addr.sin_addr.s_addr,server->h_length);
	serv_addr.sin_port = htons(portno);

	if(connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr))<0)
	{
		printf("Could not connect to host!\n");
		return -1;
	}

	printf("Connected to server port %d...\n",portno);

	memset(buffer,0,256);
	printf("Message to send: ");
	fgets(buffer,255,stdin);
	
	n = write(sockfd,buffer,strlen(buffer)-1);
	if(n<0)
	{
		printf("Error writing to socket!\n");
		close(sockfd);
		return -1;
	}
	
	if(buffer[0]=='A')
	{
	  memset(buffer,0,256);
	  printf("HWid to send: ");
	  fgets(buffer,255,stdin);
	
	  n = write(sockfd,buffer,strlen(buffer)-1);
	}

	memset(buffer,0,256);
	n = read(sockfd,buffer,255);
	if(n<0)
	{
		printf("Error reading from socket!\n");
		close(sockfd);
		return -1;
	}

  buffer[24]='\0';
  int len = atoi(buffer);//( (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]);
	//printf("Server Message: %d(length)%x%x%x%x\n",len,buffer[0],buffer[1],buffer[2],buffer[3]);
	
	printf("File length: %d\n",len);
	if(len==0)
	{
	  printf("Blank message! Probably failed authentication.\n");
	  return -1;
	}
	
	byte *fileBuffer = (byte*)malloc(sizeof(byte)*len);
	
	n = read(sockfd,fileBuffer,len);
	
	// save file
	FILE *output = fopen("Key.key","wb");
	fwrite(fileBuffer,1,len,output);
	
	fclose(output);
	
	free(fileBuffer);

	return 0;
}
